import { useState, useCallback, useEffect, useRef } from "react";
import { useDispatch } from "react-redux";
import { useNavigate } from 'react-router-dom';
import CompanyService from "../../app/services/companyService";
import { showNotification } from "../common/headerSlice";
import Pagination from "../../components/Pagination";
import PencilIcon from "@heroicons/react/24/outline/PencilIcon";
import CommonService from "../../app/services/commonService";
import PlusIcon from "@heroicons/react/24/outline/PlusIcon";
import ConfirmDialog from "../../components/ConfirmDialog";
import TitleCard from "../../components/Cards/TitleCard";
import { NotificationManager } from "react-notifications";
import { set, useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import MagnifyingGlassIcon from "@heroicons/react/24/outline/MagnifyingGlassIcon";
import CardService from "../../app/services/cardService";
import CompanyUserService from "../../app/services/companyUserService";
import CompanyAccountService from "../../app/services/companyAccountService";
import { StudentStatus } from "../../app/const/const";
import StudentPhoneModel from "./validate";
import _ from "lodash";

function StudentDeployList() {
  const dispatch = useDispatch();
  const navigate = useNavigate();

  const deployStudentRef = useRef(null);
  const callStudentPhoneRef = useRef(null);

  const [data, setData] = useState([]);
  const [total, setTotal] = useState(0);
  const [selectedRowId, setSelectedRowId] = useState(0);
  const [selectedAccountId, setSelectedAccountId] = useState(0);
  const [queryParams, setQueryParams] = useState({
    pageIndex: 1,
    accountName: '',
    userName: '',
    status: -1
  });//[pageIndex, pageSize, searchKey, status
  const [studentPhone, setStudentPhone] = useState({
    phone: ''
  });

  const [employees, setEmployees] = useState([]);

  const formOptions = { resolver: zodResolver(StudentPhoneModel.studentPhoneSchema) };
  const { register, handleSubmit, formState: { errors }, reset } = useForm(formOptions);

  const fetchData = useCallback(() => {
    CommonService.setLoading(true);
    CompanyUserService.list(queryParams).then((res) => {
      if (res.success) {
        setData(res.data);
        setTotal(res.total);
      } else {
        dispatch(
          showNotification({
            message: "获取数据失败",
            status: "error",
          })
        );
      }
    }).finally(() => {
      CommonService.setLoading(false);
    });
  }, [queryParams.pageIndex, queryParams.userName, queryParams.accountName, queryParams.status]);

  const fetchEmployees = useCallback(() => {
    CompanyAccountService.employees().then((res) => {
      if (res.success) {
        setEmployees(res.data);
      } else {
        dispatch(
          showNotification({
            message: "获取数据失败",
            status: "error",
          })
        );
      }
    });
  }, [])

  useEffect(() => {
    fetchData();
  }, [queryParams.pageIndex]);
  useEffect(() => {
    fetchEmployees();
  },[])

  const onPageChange = (pageIndex) => {
    setQueryParams({ ...queryParams, pageIndex: pageIndex });
  }

  const onSearchingData = () => {
    setQueryParams({ ...queryParams, pageIndex: 1 });
    fetchData();
  }



  const showPhoneInput = () => {
    callStudentPhoneRef.current.showModal();
  }
  const onCancelModal = () => {
    callStudentPhoneRef.current.close();
    deployStudentRef.current.close();
    setStudentPhone('');
    setSelectedRowId(0);
    setSelectedAccountId(0);
  }


  const onSubmit = (data) => {
    CardService.bind(data).then((res) => {
      if (res.success) {
        NotificationManager.success("招入信息已发送", '提示');
        callStudentPhoneRef.current.close();
        setStudentPhone('')
        fetchData();
      } else {
        NotificationManager.error(res.msg, '提示');
      }
    });
  }

  const onInvalid = (errors) => {

  }

  const userNameChanged = (e) => {
    setQueryParams({ ...queryParams, userName: e.target.value });
  }

  const accountNameChanged = (e) => {
    setQueryParams({ ...queryParams, accountName: e.target.value });
  }

  const statusChange = (e) => {
    setQueryParams({ ...queryParams, status: e.target.value });
  }

  const applyRowId = (id) => {
    setSelectedRowId(id);
    deployStudentRef.current.showModal();
  }

  const setCompanyUserGuider = () => {
    if(selectedAccountId === 0) {
      NotificationManager.error("请选择规划师", '提示')
      return;
    }
    if(selectedRowId === 0) {
      NotificationManager.error("选择考生", '提示')
      return;
    }
    CompanyUserService.bind({
      id: selectedRowId,
      accountId: selectedAccountId
    }).then((res) => {
      if (res.success) {
        NotificationManager.success("分配成功", '提示');
        deployStudentRef.current.close();
        fetchData();
      } else {
        NotificationManager.error("分配失败", '提示');
      }
    })
  }

  return (
    <>
      <dialog id="show_input_modal" ref={callStudentPhoneRef} className="modal">
        <div className="modal-box">
          <h3 className="font-bold text-lg">输入考生手机号码</h3>
          <form onSubmit={handleSubmit(onSubmit, onInvalid)}>
            <div className='form-control-inline-full my-2'>
              <label className="label">
                <div className='flex flex-row items-start justify-center' ><span className={"label-text text-base-content "}>手机号码</span></div>
              </label>
              <div>
                <input  {...register('phone')} placeholder="输入考生手机号码" />
                <p className="error">{errors.phone && errors.phone.message}</p>
              </div>
            </div>
            <div className="modal-action">
              <div className="flex flex-row items-center justify-end">
                <button type="submit" className="btn btn-primary">招入</button>
                <button className="btn btn-info mx-2" onClick={onCancelModal} >关闭</button>
              </div>
            </div>
          </form>
        </div>
      </dialog>
      <dialog id="show_employee_modal" ref={deployStudentRef} className="modal">
        <div className="modal-box">
          <h3 className="font-bold text-lg">选择规划师</h3>
            <div className='form-control-inline-full my-2'>
              <label className="label">
                <div className='flex flex-row items-start justify-center' ><span className={"label-text text-base-content "}>选择规划师</span></div>
              </label>
              <div>
                <select className="select select-bordered w-60 mx-2" value={selectedAccountId} onChange={(e) => setSelectedAccountId(e.target.value)}>
                <option  value='0'>选择规划师</option>
                  {employees.map((item, index) => {
                    return <option key={index} value={item.key}>{item.value}</option>
                  })}
                </select>
              </div>
            </div>
            <div className="modal-action">
              <div className="flex flex-row items-center justify-end">
                <button className="btn btn-primary" onClick={setCompanyUserGuider} >确定</button>
                <button className="btn btn-info mx-2" onClick={onCancelModal} >关闭</button>
              </div>
            </div>
        </div>
      </dialog>
      <div className="w-full p-4 card  bg-base-100">
        <div className="flex flex-col ">
          <div className="flex flex-row items-baseline justify-start">
            <div className="flex flex-row items-baseline justify-start mx-2">
              <div className="text-sm font-semibold">考生姓名</div>
              <input type="text" className="input input-bordered w-60  mx-2" value={queryParams.userName} onChange={userNameChanged} />
            </div>
            <div className="flex flex-row items-baseline justify-start mx-2">
              <div className="text-sm font-semibold">规划师</div>
              <input type="text" className="input input-bordered w-60  mx-2" value={queryParams.accountName} onChange={accountNameChanged} />
            </div>
            <div className="flex flex-row items-baseline justify-start mx-2" >
              <div className="text-sm font-semibold">进行状态</div>
              <select className="select select-bordered w-60 mx-2" value={queryParams.status} onChange={statusChange}>
                {StudentStatus.map((item, index) => {
                  return <option key={index} value={item.key} >{item.value}</option>
                })
                }
              </select>
            </div>
            <div className="flex flex-row items-baseline justify-start mx-2">
              <button className="btn btn-sm bg-primary text-white" onClick={onSearchingData}><MagnifyingGlassIcon className="w-4 h-4" />查询</button>
            </div>
          </div>
        </div>
      </div>
      <div className="flex flex-col">
        <TitleCard title="招入考生列表" topMargin="mt-2" TopSideButtons={
          (<div className="inline-block"><button className="btn btn-sm bg-primary text-white" onClick={showPhoneInput}><PlusIcon className="w-4 h-4" />招入考生</button></div>)} >
          <table className="table table-zebra bg-base-100 rounded-sm  border-1">
            <thead>
              <tr className=" border-b-2 border-base-100">
                <th className=" text-center">序号</th>
                <th className=" text-center">用户名</th>
                <th className=" text-center">用户基本信息</th>
                <th className=" text-center">状态</th>
                <th className=" text-center">加入时间</th>
                <th className=" text-center">规划师</th>
                <th className=" text-center">操作</th>
              </tr>
            </thead>
            <tbody>
              {data && data.length > 0 ? (
                data.map((item, index) => {
                  return (
                    <tr key={index}>
                      <th className=" text-center">{item.index}</th>
                      <td className=" text-center">{item.userName}</td>
                      <td className=" text-center">{item.userSubjects}/{item.userScore}</td>
                      <td className=" text-center">{item.userStatus}</td>
                      <td className=" text-center">{item.adminAt}</td>
                      <td className=" text-center">{item.accountName}</td>
                      <td className=" text-center">
                        <div className="flex flex-row items-center justify-around ">
                          {!item.accountId && <button className="btn btn-sm text-green-500 btn-link" onClick={() => applyRowId(item.id)}><PencilIcon className="w-4 h-4" />分配</button>}
                        </div>
                      </td>
                    </tr>
                  );
                })
              ) : (
                <tr>
                  <td colSpan="7">暂无数据</td>
                </tr>
              )}
            </tbody>
          </table>
          <div className="flex flex-row items-center justify-center">
            <Pagination currentPage={queryParams.pageIndex} totalCount={total} onPageChange={onPageChange} />
          </div>

          <div className="flex flex-col items-start justify-between text-xs my-2 p-2 bg-base-300 rounded-md" style={{ lineHeight: '20px' }}>
            <p>展示招入考生列表信息</p>
              <p>1.考生通过卡密绑定的分销商电话联系分销商，并提供自己的注册电话</p>
              <p>2.分销商通过【招入考生】功能，输入考生的注册电话，发出招入申请（有效时间10分钟）</p>
              <p>3.考生在 我的 &gt; 预约一对一指导服务 &gt; 点击 【预约服务】 </p>
              <p>4.考生预约完成，刷新招入列表，可以看到考生信息</p>
              <p>5.代理商点击【分配】按钮，选择规自己或者下级规划师，将相应的考生分配给规划师进行后续志愿单沟通操作。</p>
          </div>
        </TitleCard>
      </div>
    </>
  );
}

export default StudentDeployList;
